<template>
  <div class="supplier-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索供应商名称/联系人"
          clearable
          style="width: 300px"
          @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="primary" @click="openDialog(false)">新增供应商</el-button>
    </div>

    <!-- 供应商表格 -->
    <el-table :data="paginatedData" border stripe>
      <el-table-column prop="code" label="序号" width="200" align="center"/>
      <el-table-column prop="name" label="供应商名称" width="180" align="center"/>
      <el-table-column prop="contact" label="联系人" width="120" align="center"/>
      <el-table-column prop="phone" label="联系电话" width="150" align="center"/>
      <el-table-column prop="createdName" label="创建者" width="100" align="center"/>
      <el-table-column prop="updatedName" label="更新者" width="100" align="center"/>
      <el-table-column prop="createdTime" label="创建时间" width="180" align="center"/>
      <el-table-column prop="updatedTime" label="更新时间" width="180" align="center"/>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="text" @click="openDialog(true, row)">编辑</el-button>
          <el-button
              type="text"
              style="color: #ff4d4f"
              @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="filteredData.length"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        class="pagination"
    />

    <!-- 供应商弹窗 -->
    <el-dialog
        v-model="showDialog"
        :title="isEdit ? '编辑供应商' : '新增供应商'"
        width="600px"

    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="供应商编码" prop="code">
          <el-input
              v-model="form.code"
              placeholder="如：2SUP_HW"
              maxlength="50"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="name">
          <el-input
              v-model="form.name"
              placeholder="如：苹果官方供应商"
              maxlength="50"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="如：张经理"/>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="如：13800138000"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {addSupplier, deleteSupplier, getAllSuppliersInfo, updateSupplier} from "@/api/auth.js";

// 模拟数据（完全匹配截图内容）
const rawData = ref([
  {
    id: 1,
    code: '1SUP_CRE',
    name: '苹果官方供应商',
    contact: '张经理',
    phone: '13800138000',
    createdName: '周兴',
    updatedName: '周兴',
    createdTime: '2025-04-23 20:15:46',
    updatedTime: '2025-04-23 20:15:46'
  },
  {
    id: 2,
    code: '2SUP_HW',
    name: '华为一级代理',
    contact: '李总',
    phone: '13900139000',
    createdName: '周兴',
    updatedName: '周兴',
    createdTime: '2025-04-23 20:15:46',
    updatedTime: '2025-04-23 20:15:46'
  },
  {
    id: 3,
    code: '3SUP_FURNITURE',
    name: '家具城批发',
    contact: '王老板',
    phone: '13600136000',
    createdName: '周兴',
    updatedName: '周兴',
    createdTime: '2025-04-23 20:15:46',
    updatedTime: '2025-04-23 20:15:46'
  },
  {
    id: 4,
    code: '4SUP_SPORTS',
    name: '运动用品总代',
    contact: '陈先生',
    phone: '13500135000',
    createdName: '周兴',
    updatedName: '周兴',
    createdTime: '2025-04-23 20:15:46',
    updatedTime: '2025-04-23 20:15:46'
  }
])
const initData = async () => {
  try {
    const res = await getAllSuppliersInfo()
    if (res.code === 200) {
      rawData.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }


}
onMounted(() => {
  initData()
})

// 搜索分页逻辑
const searchKeyword = ref('')
const pagination = ref({current: 1, size: 10})

const filteredData = computed(() => {
  return rawData.value.filter(item =>
      item.name.includes(searchKeyword.value) ||
      item.contact.includes(searchKeyword.value)
  )
})

const paginatedData = computed(() => {
  const start = (pagination.value.current - 1) * pagination.value.size
  return filteredData.value.slice(start, start + pagination.value.size)
})

const handleSearch = () => pagination.value.current = 1

// 弹窗控制
const showDialog = ref(false)
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  id: '',
  code: '',
  name: '',
  contact: '',
  phone: '',
})

// 验证规则
const rules = {
  name: [
    {required: true, message: '必填项', trigger: 'blur'},
    {max: 50, message: '最多50字符', trigger: 'blur'}
  ],
  contact: [{required: true, message: '必填项', trigger: 'blur'}],
  phone: [
    {required: true, message: '必填项', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur'}
  ]
}

// 打开弹窗
const openDialog = (editMode, rowData) => {
  isEdit.value = editMode
  if (editMode && rowData) {
    Object.assign(form, rowData)
  } else {
    form.code = ``
    form.name = ''
    form.contact = ''
    form.phone = ''
  }
  showDialog.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (isEdit.value) {

      try {
        const res = await updateSupplier(form)
        if (res.code === 200) {
          ElMessage.success('修改成功')
          showDialog.value = false
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        ElMessage.error(e)
      }
    } else {

      try {
        const res = await addSupplier(form)
        if (res.code === 200) {
          ElMessage.success('添加成功!')

        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        ElMessage.error(e)
      }

    }


    showDialog.value = false
    await initData()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 删除逻辑
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确认删除供应商 "${row.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          distinguishCancelAndClose: true
        }
    )
    const res = await deleteSupplier(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功!')
      await initData()


    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {

  }
}


</script>

<style scoped>
.supplier-manage {
  padding: 20px;
  background: #fff;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}

.el-dialog .el-input {
  width: 80%;
}
</style>